package org.jet.common.controller;

import org.jet.common.comp.PathGenerator;
import org.jet.common.config.JetFileUploadConfig;
import org.jet.xmall.common.CommonResult;
import org.jet.xmall.common.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import java.util.LinkedList;
import java.util.List;


@RestController
public class FileUploadController {


    @Autowired
    private PathGenerator pathGenerator;

    @Autowired
    private JetFileUploadConfig config;


    private String saveFile(MultipartFile file) throws IOException{
        // 获取文件存储路径（绝对路径）
        String path = config.getSavePath();
        String relativeParentPath = pathGenerator.generate();
        // 获取原文件名
        String fileName = file.getOriginalFilename();

        String parentPath = path+File.separatorChar+relativeParentPath;
        File parent = new File(parentPath);
        if(!parent.exists()){
            parent.mkdirs();
        }
        System.out.println("parent="+parent.getPath());
        // 创建文件实例
        File filePath = new File(parent, fileName);
        System.out.println("filePath="+filePath.getPath());
        boolean newFile = filePath.createNewFile();
        System.out.println("newFile="+newFile);
        // 写入文件
        file.transferTo(filePath);
        return relativeParentPath+fileName;
    }



    @RequestMapping(value="/oss",method = RequestMethod.POST)
    public CommonResult<List<String>> upload(@RequestParam("file") MultipartFile[] files) throws IOException{
        if(files.length == 0){
            return CommonResult.failed(ResultCode.FAILED);
        }
        List<String> pathList = new LinkedList<>();
        for(MultipartFile file:files){
            pathList.add(saveFile(file));
        }
        return CommonResult.success(pathList,"保存文件列表成功");
    }


    @RequestMapping(value ="/oss",method = RequestMethod.DELETE)
    public CommonResult<Object> delete(@RequestBody String  url) throws IOException {
        System.out.println("收到删除文件的请求:["+url+"]");
        // http://123.57.7.108:81
        if(url.startsWith(config.getImageServer())){
            url = url.substring(config.getImageServer().length()+1);
        }
        String path = config.getSavePath()+"/"+url;
        System.out.println("请求删除文件:["+path+"]");
        File file = new File(config.getSavePath()+"/"+url);
        if(file.exists()){
            boolean delete = file.delete();
            if(delete){
                System.out.println("成功删除["+file.getAbsolutePath()+"]");
                return CommonResult.success(null,"删除文件成功");
            }
            return CommonResult.failed("文件删除失败");
        }else{
            return CommonResult.failed("文件不存在");
        }
    }
}
